﻿using AutoMapper;
using BackData;
using CSRedis;
using Domain;
using Infratructure;
using MD5Hash;
using MediatR;
using RBAC.API.Command.User;
using System.Transactions;
using Yitter.IdGenerator;

namespace RBAC.API.Handler.User
{
    public class UserAddHandler : IRequestHandler<UserAddCommand, ApiResult<int>>
    {
        private readonly IRepository<UserModel> userway;
        private readonly ILogger<UserLoginHandler> log;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        private readonly IRepository<RoleModel> roleway;
        private readonly IRepository<UserRoleModel> userroleway;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly CSRedisClient cSRedisClient;

        public UserAddHandler(IRepository<UserModel> userway, ILogger<UserLoginHandler> log,
            IMapper mapper, IConfiguration configuration, IRepository<RoleModel> roleway, IRepository<UserRoleModel> userroleway,
            IHttpContextAccessor httpContextAccessor, CSRedisClient cSRedisClient)
        {
            this.userway = userway;
            this.log = log;
            this.mapper = mapper;
            this.configuration = configuration;
            this.roleway = roleway;
            this.userroleway = userroleway;
            this.httpContextAccessor = httpContextAccessor;
            this.cSRedisClient = cSRedisClient;
        }
        /// <summary>
        /// 添加用户和用户配置的角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(UserAddCommand request, CancellationToken cancellationToken)
        {
          
            ApiResult<int> res = new ApiResult<int>();
            var i = 0;
            var j = 0;
            request.UserPwd = request.UserPwd.GetMD5();  //密码加密
            var user = mapper.Map<UserModel>(request);
            user.Id = YitIdHelper.NextId();           
            var roleids = request.RoleIds.Split(',')
                                  .Select(s => long.Parse(s.Trim()))
                                  .ToArray();
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    i = await userway.Addway(user);
                    foreach (long item in roleids)
                    {
                        UserRoleModel userrole = new UserRoleModel()
                        {
                            Id = YitIdHelper.NextId(),
                            UserId = user.Id,
                            RoleId = item,
                            IsDel = false
                        };
                        j += await userroleway.Addway(userrole);
                    }
                    tran.Complete();  //事务回滚
                    if (i > 0 && j > 0)
                    {
                        log.LogInformation($"{httpContextAccessor.HttpContext?.User.Claims.FirstOrDefault(x => x.Type == "UserName")?.Value ?? "默认值"}用户添加成功");
                        res.Message = $"用户添加成功";
                        res.Code = StateCode.OK;
                        res.Data = i + j;
                        return res;
                    }
                    else
                    {
                        res.Message = $"用户添加失败";
                        res.Code = StateCode.Fail;
                        return res;
                    }
                }
                catch (Exception ex)
                {
                    log.LogError($"{httpContextAccessor.HttpContext?.User.Claims.FirstOrDefault(x => x.Type == "UserName")?.Value ?? "默认值"}用户添加时发生异常{ex.Message}");
                    throw;
                }
            }


        }
    }
}
